package com.example.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.constant.BasePage;
import com.example.common.Re;
import com.example.entity.Employee;
import com.example.service.IEmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 员工信息
 * </p>
 *
 * @author czx
 * @since 2022-04-28
 */
@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Resource
    private IEmployeeService employeeService;

    /**
     * 员工登录
     *
     * @param request  请求
     * @param employee 员工
     * @return 结果
     */
    @PostMapping("/login")
    public Re<Employee> login(HttpServletRequest request, @RequestBody Employee employee) {
        Re<Employee> re = employeeService.login(employee);
        if (re.getCode() == 1) {
            request.getSession().setAttribute("employee", re.getData().getId());
        }
        return re;
    }

    /**
     * 员工退出
     *
     * @param request 请求
     * @return 结果
     */
    @PostMapping("/logout")
    public Re<String> logout(HttpServletRequest request) {
        request.getSession().removeAttribute("employee");
        return Re.success("退出成功");
    }

    /**
     * 新增员工
     *
     * @param employee 员工
     * @return 结果
     */
    @PostMapping
    public Re<String> save(@RequestBody Employee employee) {
        boolean save = employeeService.save(employee);
        if (save) {
            return Re.success("新增员工成功");
        }
        return Re.error("新增员工失败");
    }

    /**
     * 员工信息分页查询
     *
     * @param basePage 分页大小
     * @param name     员工名
     * @return 结果
     */
    @GetMapping("/page")
    public Re<Page<Employee>> page(BasePage basePage, String name) {
        Page<Employee> pageInfo = employeeService.page(basePage.getPage(), basePage.getPageSize(), name);

        return Re.success(pageInfo);
    }

    /**
     * 根据id修改员工信息
     *
     * @param employee 员工信息
     * @return 结果
     */
    @PutMapping
    private Re<String> update(@RequestBody Employee employee) {
        long id = Thread.currentThread().getId();
        log.info("线程id为：{}", id);

        boolean update = employeeService.updateById(employee);
        if (update) {
            return Re.success("员工信息修改成功");
        }
        return Re.error("员工信息修改失败");
    }

    /**
     * 根据id回显员工信息
     *
     * @param id id
     * @return 修改的结果
     */
    @GetMapping("{id}")
    public Re<Employee> getById(@PathVariable Long id) {
        Employee employee = employeeService.getById(id);
        if (employee != null) {
            return Re.success(employee);
        }
        return Re.error("找不到该账号");
    }
}
